import React from 'react'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { MoreHorizontal, Trash2, Edit, ArrowRight, Clock } from 'lucide-react'
import { Task } from '../types'
import { TimeLabel, TaskTag, PriorityLabel, CategoryLabel } from './Tags'

interface KanbanTaskCardProps {
  task: Task
  onClick: (taskId: string) => void
  onDelete?: (taskId: string) => void
  isDragging?: boolean
  onMoveToColumn?: (taskId: string, newStatus: string) => void
  availableColumns?: Array<{id: string, title: string, status: string, color: string}>
  isMobileView?: boolean
}

export default function KanbanTaskCard({ 
  task, 
  onClick, 
  onDelete, 
  isDragging, 
  onMoveToColumn,
  availableColumns,
  isMobileView 
}: KanbanTaskCardProps) {
  const [showMenu, setShowMenu] = React.useState(false)
  
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging: isSortableDragging,
  } = useSortable({ 
    id: task.id,
    data: {
      type: 'task',
      task
    },
    // 在移动端降低拖拽敏感度，避免与滑动手势冲突
    disabled: isMobileView && availableColumns && availableColumns.length > 1
  })


  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isSortableDragging || isDragging ? 0.5 : 1,
  }

  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    onClick(task.id)
  }

  const handleMenuClick = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setShowMenu(!showMenu)
  }

  const handleDelete = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (onDelete && confirm('确定要删除这个任务吗？')) {
      onDelete(task.id)
    }
    setShowMenu(false)
  }

  const handleEdit = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    onClick(task.id)
    setShowMenu(false)
  }

  const handleMoveToColumn = (e: React.MouseEvent, newStatus: string) => {
    e.preventDefault()
    e.stopPropagation()
    if (onMoveToColumn) {
      onMoveToColumn(task.id, newStatus)
    }
    setShowMenu(false)
  }



  const getStatusColor = (status: string) => {
    switch (status) {
      case 'todo': return 'border-l-slate-400'
      case 'in_progress': return 'border-l-blue-400'
      case 'review': return 'border-l-orange-400'
      case 'done': return 'border-l-green-400'
      default: return 'border-l-gray-400'
    }
  }

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className={`
        group bg-white rounded-lg border border-slate-200 p-3 mb-2 shadow-sm
        hover:shadow-md transition-all duration-200 cursor-pointer touch-manipulation
        border-l-4 ${getStatusColor(task.status)}
        ${isSortableDragging || isDragging ? 'opacity-50 rotate-2 scale-105 shadow-lg' : ''}
        ${task.completed ? 'opacity-75' : ''}
        min-h-[110px] sm:min-h-[120px]
      `}
      onClick={handleClick}
    >
      {/* 任务标题和操作按钮 */}
      <div className="flex items-start justify-between mb-2">
        <h3 className={`
          text-sm font-medium text-slate-900 line-clamp-2 flex-1 pr-2
          ${task.completed ? 'line-through text-slate-500' : ''}
        `}>
          {task.title}
        </h3>
        <div className="flex items-center gap-1 flex-shrink-0">
          {task.completed && (
            <div className="w-4 h-4 text-green-500">✓</div>
          )}
          <div className="relative">
            <button
              onClick={handleMenuClick}
              className="p-1 hover:bg-gray-100 rounded transition-colors opacity-0 group-hover:opacity-100"
            >
              <MoreHorizontal className="w-3 h-3 text-gray-500" />
            </button>
            
            {/* 下拉菜单 */}
            {showMenu && (
              <div className="absolute right-0 top-6 bg-white border border-gray-200 rounded-lg shadow-lg z-[60] min-w-[120px]">
                <button
                  onClick={handleEdit}
                  className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-t-lg"
                >
                  <Edit className="w-3 h-3" />
                  编辑
                </button>
                
                {/* 移动端显示移动选项 */}
                {isMobileView && availableColumns && availableColumns.length > 1 && 
                 availableColumns.filter(col => col.status !== task.status).length > 0 && (
                  <div className="border-t border-gray-100">
                    <div className="px-3 py-2 text-xs text-gray-500 font-medium">移动到</div>
                    {availableColumns
                      .filter(col => col.status !== task.status)
                      .map(column => (
                        <button
                          key={column.id}
                          onClick={(e) => handleMoveToColumn(e, column.status)}
                          className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50"
                        >
                          <div 
                            className="w-3 h-3 rounded-full flex-shrink-0"
                            style={{ backgroundColor: column.color }}
                          />
                          <ArrowRight className="w-3 h-3" />
                          {column.title}
                        </button>
                      ))
                    }
                  </div>
                )}
                
                <button
                  onClick={handleDelete}
                  className="w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50 rounded-b-lg border-t border-gray-100"
                >
                  <Trash2 className="w-3 h-3" />
                  删除
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 任务描述 */}
      {task.description && (
        <p className="text-xs text-slate-600 mb-2 line-clamp-2 leading-relaxed">
          {task.description}
        </p>
      )}

      {/* 子任务进度 */}
      {task.subtasks && task.subtasks.length > 0 && (
        <div className="flex items-center gap-2 mb-2">
          <div className="flex-1 bg-slate-100 rounded-full h-1.5">
            <div 
              className="bg-blue-500 h-1.5 rounded-full transition-all duration-300"
              style={{ 
                width: `${(task.subtasks.filter(s => s.completed).length / task.subtasks.length) * 100}%` 
              }}
            />
          </div>
          <span className="text-xs text-slate-500 font-medium">
            {task.subtasks.filter(s => s.completed).length}/{task.subtasks.length}
          </span>
        </div>
      )}

      {/* 优先级和分类标签区域 - 靠右对齐 */}
      <div className="flex flex-wrap items-center justify-end gap-1.5 mb-2">
        <PriorityLabel priority={task.priority} />
        <CategoryLabel category={task.category} />
      </div>

      {/* 底部元信息区域 - 任务标签、创建时间和到期时间在一行 */}
      <div className="flex items-center justify-between mt-3 pt-3 border-t border-slate-100">
        {/* 左侧：任务标签 - 看板空间有限，只显示1个标签 */}
        <TaskTag tags={task.tags || []} maxDisplay={1} />
        
        {/* 右侧：创建时间和到期时间 */}
        <div className="flex items-center gap-2">
          {/* 创建时间 - 简化显示 */}
          <div className="flex items-center gap-1 text-xs text-slate-500">
            <Clock className="w-3 h-3" />
            <span>
              {(() => {
                const now = new Date()
                const created = new Date(task.createdAt)
                const diffMs = now.getTime() - created.getTime()
                const diffMinutes = Math.floor(diffMs / (1000 * 60))
                const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
                const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
                
                if (diffMinutes < 60) return `${diffMinutes}分钟前`
                if (diffHours < 24) return `${diffHours}小时前`
                if (diffDays < 7) return `${diffDays}天前`
                return created.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
              })()}
            </span>
          </div>

          {/* 到期时间标签 - 只在有截止日期时显示 */}
          <TimeLabel task={task} />
        </div>
      </div>
    </div>
  )
}
